package com.young.common.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 集合类操作工具
 *
 * @author ：<a href="mailto:youngkun2016@163.com">young</a>
 * @date ：Created in 2020/4/29
 */
public class CollectionsUtils {
    private static Logger logger = LogManager.getLogger(CollectionsUtils.class);
    private static ObjectMapper objectMapper = new ObjectMapper();

    /**
     * ArrayList 深克隆
     * 本质：序列化与反序列化
     * {@link ObjectMapper}版本可能会影响到这个方法的结果
     *
     * @param source
     * @param type
     * @param <T>
     * @return
     */
    public static <T> List<T> copyOf(List<T> source, Class<T> type) {
        List<T> target = new ArrayList<>(source.size());
        source.stream().forEach(d -> {
            try {
                String jsonString = objectMapper.writeValueAsString(d);
                target.add(objectMapper.readValue(jsonString, type));
            } catch (JsonProcessingException e) {
                logger.error("object convert to json string failed", e.getMessage());
                throw new RuntimeException(e);
            } catch (IOException e) {
                logger.error("json string convert to object failed", e.getMessage());
                throw new RuntimeException(e);
            }
        });
        return target;
    }
}
